package com.huanzhidadi.single.threadlocal;

import org.springframework.util.StopWatch;

public class ThreadContentTest {

    private String content;

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public static void main(String[] args) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("没有同步机制");
        ThreadContentTest threadContentTest = new ThreadContentTest();
        for (int i=0; i<6; i++) {
            new Thread(() -> {
                // 由于没有进行同步控制，不能保证同一时间只有一个线程进行操作，当前线程获取到的可能是其他线程设置的内容
                threadContentTest.setContent(Thread.currentThread().getName() + "的数据");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "\t  " + threadContentTest.getContent());
            }, String.valueOf(i)).start();
        }
        // 所有线程累加完成后输出 如果除了主线程外还有子线程存在，则主线程让出执行时间
        while (Thread.activeCount() > 2) Thread.yield();
        stopWatch.stop();
        System.out.println(stopWatch.getTotalTimeMillis() + "ms");
    }
}
